package com.damai.pay;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import com.citywithincity.pay.PayException;
import com.damai.error.ApiError;

public abstract class AbsPayModel<BusinessOrder> implements PayAdapterListener {
	
	protected PayAdapter<?>[] adapters;
	public AbsPayModel() {
		adapters = new PayAdapter[10];
	}
	
	protected abstract Object fromOrder(BusinessOrder order);

	public Object prePay(BusinessOrder order,HttpServletRequest request) throws IOException{
		PayAdapter<Object> adapter = getAdapter(order);
		if(adapter==null){
			throw new ApiError("支付方式不存在");
		}
		Object realOrder = fromOrder(order );
		return adapter.prePay(realOrder, request);
	}
	
	public void refund(BusinessOrder order) throws PayException, IOException{
		PayAdapter<Object> adapter = getAdapter(order);
		if(adapter==null){
			throw new ApiError("支付方式不存在");
		}
		Object realOrder = fromOrder(order );
		adapter.refund(realOrder);
	}

	
	/**
	 * 获取支付适配器
	 * @param order
	 * @return
	 */
	public PayAdapter<Object> getAdapter(BusinessOrder order){
		return getAdapter(getType(order));
	}
	
	
	@SuppressWarnings("unchecked")
	public PayAdapter<Object> getAdapter(int type){
		return (PayAdapter<Object>) adapters[type];
	}

	protected abstract int getType(BusinessOrder order);
	

}
